package com.uduemc.biso.node.module.service.impl;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.uduemc.biso.node.core.entities.SDownloadAttr;
import com.uduemc.biso.node.module.mapper.SDownloadAttrMapper;
import com.uduemc.biso.node.module.service.SDownloadAttrContentService;
import com.uduemc.biso.node.module.service.SDownloadAttrService;

import cn.hutool.core.collection.CollUtil;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class SDownloadAttrServiceImpl implements SDownloadAttrService {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private SDownloadAttrMapper sDownloadAttrMapper;

	@Autowired
	private SDownloadAttrContentService sDownloadAttrContentServiceImpl;

	@Override
	public SDownloadAttr insertAndUpdateCreateAt(SDownloadAttr sDownloadAttr) {
		sDownloadAttrMapper.insert(sDownloadAttr);
		SDownloadAttr findOne = findOne(sDownloadAttr.getId());
		Date createAt = sDownloadAttr.getCreateAt();
		if (createAt != null) {
			sDownloadAttrMapper.updateCreateAt(findOne.getId(), createAt, SDownloadAttr.class);
		}
		return findOne;
	}

	@Override
	public SDownloadAttr insert(SDownloadAttr sDownloadAttr) {
		sDownloadAttrMapper.insert(sDownloadAttr);
		return findOne(sDownloadAttr.getId());
	}

	@Override
	public SDownloadAttr insertSelective(SDownloadAttr sDownloadAttr) {
		sDownloadAttrMapper.insertSelective(sDownloadAttr);
		return findOne(sDownloadAttr.getId());
	}

	@Override
	public SDownloadAttr updateById(SDownloadAttr sDownloadAttr) {
		sDownloadAttrMapper.updateByPrimaryKey(sDownloadAttr);
		return findOne(sDownloadAttr.getId());
	}

	@Override
	public SDownloadAttr updateByIdSelective(SDownloadAttr sDownloadAttr) {
		sDownloadAttrMapper.updateByPrimaryKeySelective(sDownloadAttr);
		return findOne(sDownloadAttr.getId());
	}

	@Override
	public SDownloadAttr findOne(Long id) {
		return sDownloadAttrMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<SDownloadAttr> findAll(Pageable pageable) {
		int pageNumber = pageable.getPageNumber();
		int pageSize = pageable.getPageSize();
		PageHelper.startPage(pageNumber, pageSize);
		return sDownloadAttrMapper.selectAll();
	}

	@Override
	public void deleteById(Long id) {
		sDownloadAttrMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int deleteByHostSiteId(long hostId, long siteId) {
		Example example = new Example(SDownloadAttr.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("siteId", siteId);
		return sDownloadAttrMapper.deleteByExample(example);
	}

	@Override
	@Transactional
	public boolean initSystemData(long hostId, long siteId, long systemId) {
		String errorMessage;
		// 排序号
		SDownloadAttr orderNumber = new SDownloadAttr();
		orderNumber.setHostId(hostId).setSiteId(siteId).setSystemId(systemId).setTitle("序号").setType((short) 1).setProportion("10").setIsShow((short) 1)
				.setIsSearch((short) 0).setOrderNum(1);

		// 分类名称
		SDownloadAttr categoryName = new SDownloadAttr();
		categoryName.setHostId(hostId).setSiteId(siteId).setSystemId(systemId).setTitle("类别").setType((short) 2).setProportion("30").setIsShow((short) 0)
				.setIsSearch((short) 0).setOrderNum(2);

		// 名称
		SDownloadAttr sDownloadItem = new SDownloadAttr();
		sDownloadItem.setHostId(hostId).setSiteId(siteId).setSystemId(systemId).setTitle("名称").setType((short) 3).setProportion("-1").setIsShow((short) 1)
				.setIsSearch((short) 1).setOrderNum(3);

		// 下载
		SDownloadAttr downOperation = new SDownloadAttr();
		downOperation.setHostId(hostId).setSiteId(siteId).setSystemId(systemId).setTitle("下载").setType((short) 4).setProportion("20").setIsShow((short) 1)
				.setIsSearch((short) 0).setOrderNum(4);

		int insert = sDownloadAttrMapper.insert(orderNumber);
		if (insert < 0) {
			errorMessage = "插入 SDownloadItem 失败 orderNumber:" + orderNumber.toString();
			logger.error(errorMessage);
			throw new RuntimeException(errorMessage);
		}
		insert = sDownloadAttrMapper.insert(categoryName);
		if (insert < 0) {
			errorMessage = "插入 SDownloadItem 失败 categoryName:" + categoryName.toString();
			logger.error(errorMessage);
			throw new RuntimeException(errorMessage);
		}
		insert = sDownloadAttrMapper.insert(sDownloadItem);
		if (insert < 0) {
			errorMessage = "插入 SDownloadItem 失败 sDownloadItem:" + sDownloadItem.toString();
			logger.error(errorMessage);
			throw new RuntimeException(errorMessage);
		}
		insert = sDownloadAttrMapper.insert(downOperation);
		if (insert < 0) {
			errorMessage = "插入 SDownloadItem 失败 downOperation:" + downOperation.toString();
			logger.error(errorMessage);
			throw new RuntimeException(errorMessage);
		}
		return true;
	}

	@Override
	public List<SDownloadAttr> findByHostSiteSystemId(long hostId, long siteId, long systemId) {
		Example example = new Example(SDownloadAttr.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("siteId", siteId);
		criteria.andEqualTo("systemId", systemId);
		example.setOrderByClause("`order_num` ASC, `id` ASC");
		return sDownloadAttrMapper.selectByExample(example);
	}

	@Override
	public SDownloadAttr findByHostSiteSystemIdAndType(long hostId, long siteId, long systemId, short type) {
		Example example = new Example(SDownloadAttr.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("siteId", siteId);
		criteria.andEqualTo("systemId", systemId);
		criteria.andEqualTo("type", type);
		example.setOrderByClause("`order_num` ASC, `id` ASC");
		List<SDownloadAttr> selectByExample = sDownloadAttrMapper.selectByExample(example);
		if (CollUtil.isEmpty(selectByExample)) {
			return null;
		}
		return selectByExample.get(0);
	}

	@Override
	public SDownloadAttr findByHostSiteIdAndId(long hostId, long siteId, long id) {
		Example example = new Example(SDownloadAttr.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("id", id);
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("siteId", siteId);
		List<SDownloadAttr> selectByExample = sDownloadAttrMapper.selectByExample(example);
		if (CollectionUtils.isEmpty(selectByExample)) {
			return null;
		}
		return selectByExample.get(0);
	}

	@Override
	@Transactional
	public boolean saves(List<SDownloadAttr> listSDownloadAttr) {
		for (SDownloadAttr sDownloadAttr : listSDownloadAttr) {
			int row = 0;
			if (sDownloadAttr.getId() == null || sDownloadAttr.getId().longValue() < 1) {
				sDownloadAttr.setId(null);
				row = sDownloadAttrMapper.insert(sDownloadAttr);
				if (row < 1) {
					throw new RuntimeException("saves 写入数据失败 sDownloadAttr: " + sDownloadAttr.toString());
				}
			} else {
				sDownloadAttrMapper.updateByPrimaryKeySelective(sDownloadAttr);
			}
		}
		return true;
	}

	@Override
	public List<SDownloadAttr> findGreaterThanOrEqualToByAfterId(long hostId, long siteId, long afterId) {
		SDownloadAttr afterSDownloadAttr = findByHostSiteIdAndId(hostId, siteId, afterId);
		if (afterSDownloadAttr == null) {
			return null;
		}
		return findGreaterThanOrEqualToByAfterId(afterSDownloadAttr);
	}

	@Override
	public List<SDownloadAttr> findGreaterThanOrEqualToByAfterId(SDownloadAttr afterSDownloadAttr) {
		Integer orderNum = afterSDownloadAttr.getOrderNum();
		Example example = new Example(SDownloadAttr.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", afterSDownloadAttr.getHostId());
		criteria.andEqualTo("siteId", afterSDownloadAttr.getSiteId());
		criteria.andEqualTo("systemId", afterSDownloadAttr.getSystemId());
		criteria.andGreaterThanOrEqualTo("orderNum", orderNum);
		example.setOrderByClause("`order_num` ASC, `id` ASC");
		return sDownloadAttrMapper.selectByExample(example);
	}

	@Override
	@Transactional
	public boolean deleteByHostSiteAttrId(long hostId, long siteId, long attrId) {
		Example example = new Example(SDownloadAttr.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("id", attrId);
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("siteId", siteId);
		List<SDownloadAttr> selectByExample = sDownloadAttrMapper.selectByExample(example);
		if (!CollectionUtils.isEmpty(selectByExample)) {
			int deleteByExample = sDownloadAttrMapper.deleteByExample(example);
			if (deleteByExample < 1) {
				throw new RuntimeException("删除 SDownloadAttr 数据失败！ deleteByHostSiteAttrId(long hostId, long siteId, long attrId) hostId: " + hostId
						+ " siteId: " + siteId + " attrId: " + attrId);
			}
		}

		// 删除 s_download_attr_content 中的数据
		boolean deleteByHostSiteAttrId = sDownloadAttrContentServiceImpl.deleteByHostSiteAttrId(hostId, siteId, attrId);
		if (!deleteByHostSiteAttrId) {
			throw new RuntimeException("删除 SDownloadAttrContent 数据失败！ deleteByHostSiteAttrId(long hostId, long siteId, long attrId) hostId: " + hostId
					+ " siteId: " + siteId + " attrId: " + attrId);
		}

		// 重新排序
		SDownloadAttr sDownloadAttr = selectByExample.get(0);
		Integer orderNum = sDownloadAttr.getOrderNum();
		int orderNumTime = orderNum.intValue();
		logger.info("重新排序: " + orderNumTime);
		List<SDownloadAttr> listSDownloadAttr = findGreaterThanOrEqualToByAfterId(sDownloadAttr);
		logger.info("重新排序 listSDownloadAttr: " + listSDownloadAttr);
		if (!CollectionUtils.isEmpty(listSDownloadAttr)) {
			for (SDownloadAttr sDownloadAttr2 : listSDownloadAttr) {
				sDownloadAttr2.setOrderNum(orderNumTime);
				SDownloadAttr updateById = updateById(sDownloadAttr2);
				if (updateById.getId().longValue() != sDownloadAttr2.getId().longValue()) {
					throw new RuntimeException("重新排序失败！listSDownloadAttr: " + listSDownloadAttr);
				}
				orderNumTime = orderNumTime + 1;
			}
		}

		return true;
	}

	@Override
	public boolean existByHostSiteIdAndIdList(long hostId, long siteId, List<Long> ids) {
		Example example = new Example(SDownloadAttr.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("siteId", siteId);
		criteria.andIn("id", ids);
		int selectCountByExample = sDownloadAttrMapper.selectCountByExample(example);
		if (selectCountByExample == ids.size()) {
			return true;
		}
		return false;
	}

	@Override
	public boolean deleteByHostSiteSystemId(long hostId, long siteId, long systemId) {
		Example example = new Example(SDownloadAttr.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("siteId", siteId);
		criteria.andEqualTo("systemId", systemId);
		int selectCountByExample = sDownloadAttrMapper.selectCountByExample(example);
		if (selectCountByExample < 1) {
			return true;
		}
		return sDownloadAttrMapper.deleteByExample(example) == selectCountByExample;
	}

	@Override
	public PageInfo<SDownloadAttr> findPageInfoAll(long hostId, long siteId, int pageNum, int pageSize) {
		Example example = new Example(SDownloadAttr.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("siteId", siteId);
		PageHelper.startPage(pageNum, pageSize);
		List<SDownloadAttr> listSDownloadAttr = sDownloadAttrMapper.selectByExample(example);
		PageInfo<SDownloadAttr> result = new PageInfo<>(listSDownloadAttr);
		return result;
	}

	@Override
	public PageInfo<SDownloadAttr> findPageInfoAll(long hostId, long siteId, long systemId, int pageNum, int pageSize) {
		Example example = new Example(SDownloadAttr.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("siteId", siteId);
		criteria.andEqualTo("systemId", systemId);
		PageHelper.startPage(pageNum, pageSize);
		List<SDownloadAttr> listSDownloadAttr = sDownloadAttrMapper.selectByExample(example);
		PageInfo<SDownloadAttr> result = new PageInfo<>(listSDownloadAttr);
		return result;
	}

}
